package net.zigin.nhi.waste.view.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.CustomAdapter;
import net.zigin.nhi.waste.bean.MenuVoBean;
import net.zigin.nhi.waste.bean.NotifyBean;
import net.zigin.nhi.waste.bean.UserLogoutSuccessEvent;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.scan.CodeListener;
import net.zigin.nhi.waste.scan.CodeReceiver;
import net.zigin.nhi.waste.utils.DateUtils;
import net.zigin.nhi.waste.utils.BitmapUtils;
import net.zigin.nhi.waste.utils.DialogUtil;
import net.zigin.nhi.waste.utils.OpenFile;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.alarm.AlarmActivity;
import net.zigin.nhi.waste.view.collect.OfficeScanActivity;
import net.zigin.nhi.waste.view.history.DepotHistoryActivity;
import net.zigin.nhi.waste.view.depotin.CollectorActivity;
import net.zigin.nhi.waste.view.depotout.DepotOutActivity;
import net.zigin.nhi.waste.view.history.HistoryActivity;
import net.zigin.nhi.waste.view.history.ScanRecordActivity;
import net.zigin.nhi.waste.view.mine.PersonalActivity;
import net.zigin.nhi.waste.view.notify.NotifyActivity;
import net.zigin.nhi.waste.view.print.CodePrintActivity;
import net.zigin.nhi.waste.view.widget.DialogManager;
import net.zigin.nhi.waste.view.widget.SpaceItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.paperdb.Paper;
import io.reactivex.Observable;
import me.goldze.mvvmhabit.http.DownLoadManager;
import me.goldze.mvvmhabit.http.download.ProgressCallBack;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.ResponseBody;


public class MainActivity extends AppCompatActivity implements CodeListener, View.OnClickListener {

    private CodeReceiver receiver;
    private RecyclerView mList;
    private TextView mName;
    private TextView mRole;
    private ImageView mHeadPic;
    private TextView mHospitalName;
    private TextView mNotifyTv;
    private TextView mNotifyTime;
    private ImageView mSettings;
    private LinearLayout mNotifyLayout;
    private LinearLayout mScanLayout;
    private LinearLayout mDepotLayout;
    private LinearLayout mPrintLayout;
    private LinearLayout mAlarmLayout;

    private NotificationCompat.Builder builder;
    private NotificationManager manager;

    private RxPermissions rxPermissions;

    private DialogUtil dialogUtil;
    public static final int NO_3 = 0x3;

    private String token;
    private CustomAdapter adapter;
    private List<MenuVoBean> menuList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView();
        initReceiver();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
        getNoticeMessage();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        ImmersionBar.with(this).init();
        rxPermissions = new RxPermissions(this);
        mList = findViewById(R.id.list);
        mName = findViewById(R.id.name);
        mRole = findViewById(R.id.role);
        mHeadPic = findViewById(R.id.headPic);
        mHospitalName = findViewById(R.id.hospitalName);
        mNotifyTv = findViewById(R.id.notify_tv);
        mNotifyTime = findViewById(R.id.notify_time);
        mNotifyLayout = findViewById(R.id.notify_layout);
        mScanLayout = findViewById(R.id.scan_layout);
        mDepotLayout = findViewById(R.id.depot_layout);
        mPrintLayout = findViewById(R.id.print_layout);
        mAlarmLayout = findViewById(R.id.alarm_layout);
        mSettings = findViewById(R.id.settings);

        mSettings.setOnClickListener(this);
        mNotifyLayout.setOnClickListener(this);
        mScanLayout.setOnClickListener(this);
        mDepotLayout.setOnClickListener(this);
        mPrintLayout.setOnClickListener(this);
        mAlarmLayout.setOnClickListener(this);
    }

    /**
     * 初始化广播接收器
     */
    private void initReceiver() {
        receiver = new CodeReceiver();
        receiver.setListener(this);
        registerReceiver(receiver, new IntentFilter("com.barcode.sendBroadcast"));
    }

    /**
     * 初始化数据
     */
    private void initData() {

        rxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                });

        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(getApplicationContext(), createNotificationChannel(this));
        checkUpdate();


        token = Paper.book().read(Constants.TOKEN);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        //设置等宽间距
        mList.addItemDecoration(new SpaceItemDecoration(15));
        mList.setLayoutManager(manager);
        menuList = Paper.book().read(Constants.MENULIST);
        if (menuList != null && menuList.size() > 0) {
            adapter = new CustomAdapter(menuList);
            mList.setAdapter(adapter);

            adapter.setOnItemClickListener((view, url) -> {
                switch (url) {
                    case "depot_out"://医废出库
                        Intent intent1 = new Intent(MainActivity.this, DepotOutActivity.class);
                        startActivity(intent1);
                        break;
                    case "trace_record"://医废追溯
                        Intent intent2 = new Intent(MainActivity.this, HistoryActivity.class);
                        startActivity(intent2);
                        break;
                    case "collect_collect"://医废收集
                        Intent intent3 = new Intent(MainActivity.this, OfficeScanActivity.class);
                        startActivity(intent3);
                        break;
                    case "depot_in"://医废入库
                        Intent intent4 = new Intent(MainActivity.this, CollectorActivity.class);
                        startActivity(intent4);
                        break;
                }
            });
        }
    }

    /**
     * 设置个人信息
     */
    private void getUserInfo() {
        String id = Paper.book().read(Constants.STAFFID);
        if (token != null && id != null) {
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getStaffInfoById(token, id);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    Log.i("个人信息", data);
                    JSONObject object = JSON.parseObject(data);
                    String realName = object.getString("realName");
                    String roleName = object.getString("roleName");
                    String hospitalName = object.getString("hospitalName");
                    String headPicUrl = object.getString("headPic");
                    if (realName != null) {
                        mName.setText(realName);
                        Paper.book().write(Constants.REALNAME, realName);
                    }
                    if (roleName != null) {
                        mRole.setText(roleName);
                    }
                    if (hospitalName != null) {
                        mHospitalName.setText(hospitalName);
                        Paper.book().write(Constants.HOSPITAL_NAME, hospitalName);
                    }
                    if (headPicUrl != null) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap = BitmapUtils.urlToBitmap(headPicUrl, MainActivity.this);
                                Bitmap roundBitmap = BitmapUtils.toRoundBitmap(bitmap);
                                runOnUiThread(() -> {
                                    mHeadPic.setImageBitmap(roundBitmap);
                                });
                            }
                        }).start();
                    }

                }
            });
        }
    }

    /**
     * 获取当前用户未读的公告
     */
    private void getNoticeMessage() {
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getCurrentNoticeList(token);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {
                Log.i("首页公告", data);
                DateUtils util = new DateUtils();
                String time = "";
                List<NotifyBean> list = JSONArray.parseArray(data, NotifyBean.class);
                if (data != null && list != null && list.size() > 0) {
                    mNotifyTv.setText(list.get(0).getContent());
                    time = list.get(0).getCreateTime();
                    Date date = util.strToDateLong(time);
                    mNotifyTime.setText(util.timeUtil(date));
                } else {
                    mNotifyTv.setText("暂无新公告！");
                    mNotifyTime.setText("");
                }
            }
        });
    }

    /**
     * 检查版本更新
     */
    private void checkUpdate() {
        PackageInfo packageInfo = null;
        try {
            packageInfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        int localVersion = packageInfo.versionCode;
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .checkUpdate();
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    JSONObject object = JSON.parseObject(data);
                    if (localVersion < object.getInteger("num")) {
                        dialogUtil = new DialogUtil(MainActivity.this, "新版本", "有新版本，是否立刻更新", "是", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                download(object.getString("url"));
                                dialogUtil.dismissDialog();
                            }
                        }, "否", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialogUtil.dismissDialog();
                            }
                        });
                        dialogUtil.showDialog();
                    }
                }
            }
        });
    }

    /**
     * 下载文件
     *
     * @param loadUrl
     */
    public void download(String loadUrl) {
        ToastUtils.showLong("开始下载...");
        String destFileDir = getExternalFilesDir("file").getAbsolutePath();  //文件存放的路径
        String destFileName = System.currentTimeMillis() + ".apk";//文件存放的名称
        final String path = destFileDir + "/" + destFileName;
        setPermission(path);
        DownLoadManager.getInstance().load(loadUrl, new ProgressCallBack<ResponseBody>(destFileDir, destFileName) {
            @Override
            public void onStart() {
                //RxJava的onStart()
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setContentTitle("下载");
                manager.notify(NO_3, builder.build());
                builder.setProgress(100, 0, false);
            }

            @Override
            public void onCompleted() {

            }

            @Override
            public void onSuccess(ResponseBody responseBody) {
                builder.setContentTitle("开始安装");
                manager.cancel(NO_3);//设置关闭通知栏
                Intent intent = OpenFile.openFile(MainActivity.this, new File(path));

                if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    startActivity(intent);
                }


            }

            @Override
            public void progress(final long progress, final long total) {
                //下载中的回调 progress：当前进度 ，total：文件总大小
                builder.setProgress(100, (int) progress, false);
                manager.notify(NO_3, builder.build());
                //下载进度提示
                builder.setContentText("下载" + progress + "%");
            }

            @Override
            public void onError(Throwable e) {
                //下载错误回调
                ToastUtils.showShort("下载失败");
                builder.setContentTitle("下载失败");
            }
        });
    }


    public void setPermission(String filePath) {
        String command = "chmod " + "777" + " " + filePath;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 前台通知
     *
     * @param context
     * @return
     */
    public String createNotificationChannel(Context context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "channelId";
            CharSequence channelName = "channelName";
            String channelDescription = "channelDescription";
            int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
            // 设置描述 最长30字符
            notificationChannel.setDescription(channelDescription);
            // 该渠道的通知是否使用震动
            //notificationChannel.enableVibration(true);
            // 设置显示模式
            notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);

            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            return null;
        }
    }


    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
            System.gc();
        }
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void getData(String data) {
        Log.i("扫码结果", data);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.settings://个人设置
                Intent intent1 = new Intent(MainActivity.this, PersonalActivity.class);
                startActivity(intent1);
                break;
            case R.id.notify_layout://公告
                Intent intent2 = new Intent(MainActivity.this, NotifyActivity.class);
                startActivity(intent2);
                break;
            case R.id.scan_layout://扫一扫
                //开启扫描
                Intent intent3 = new Intent(MainActivity.this, ScanRecordActivity.class);
                startActivity(intent3);
                break;
            case R.id.depot_layout://出入库
                Intent intent4 = new Intent(MainActivity.this, DepotHistoryActivity.class);
                startActivity(intent4);
                break;
            case R.id.print_layout://条码打印
                Intent intent5 = new Intent(MainActivity.this, CodePrintActivity.class);
                startActivity(intent5);
                break;
            case R.id.alarm_layout://告警信息
                Intent intent6 = new Intent(MainActivity.this, AlarmActivity.class);
                startActivity(intent6);
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userLogout(UserLogoutSuccessEvent event) {
        finish();
    }
}